<?php

declare(strict_types=1);

namespace App\CustHub\Request;

use App\Common\Constants\SmsEventConstants;
use App\Common\Service\SmsService;
use App\CustHub\Service\ChUserService;
use App\System\Model\SystemUser;
use Mine\Exception\NormalStatusException;
use Mine\MineFormRequest;

class UserRequest extends MineFormRequest
{
    /**
     * 修改密码验证规则
     * return array.
     */
    public function modifyPasswordRules(): array
    {
        return [
            'newPassword' => 'required|confirmed|string',
            'newPassword_confirmation' => 'required|string',
            'oldPassword' => ['required', function ($attribute, $value, $fail) {
                $service = $this->container->get(ChUserService::class);
                /**
                 * @var SystemUser $model
                 */
                $model = $service->mapper->getModel()::find((int) chUser()->getId(), ['password']);
                if (! $service->mapper->checkPass($value, $model->password)) {
                    $fail(t('system.valid_password'));
                }
            }],
            'code' => ['required',function ($attribute, $value, $fail) {
                $userService = $this->container->get(ChUserService::class);
                $userInfo = $userService->mapper->findById(chUser()->getId());
                $smsService = make(SmsService::class, [SmsEventConstants::CH_EDIT_PASS]);
                if (!$smsService->verifyCode($userInfo->mobile, $value)) {
                    $fail("验证码无效");
                }
            }]
        ];
    }

    public function saveNotifyConfigRules(): array
    {
        return [
            'id' => 'required',
            'notify_switch' => 'required|in:0,1',
        ];
    }
}